#! /usr/bin/env python
# -*- coding: utf-8 -*-
# #############################################################
# flac2ogg
#  convert flac audio files to ogg
#  convertir facilement les fichiers flac vers oggg
#
# Ce programme est livree sans aucune garantie sous les terme 
# de la licence GPL
# Edite par mzalim 
# sous licence GPL 
#
# Un programmeur ne copie pas il s'inspire , lire les termes 
# de la licence gpl.txt
# 
# Version du programme 0.1.0
# Date de production Fri Oct 10 14:13:00 2008
#
# This software is delivered withount any wanranty
# under the terms of the General Public licence
# see the gpl.txt 
#
# For more informations
# http://code.google.com/p/moufid
# #############################################################

#imports
import os, sys, commands
from utils import *
from optparse import OptionParser


#constants
# Extensions of free lossless audio codec encoded files
__NON_COMPRESSED_MUSIC_EXTENSIONS__ = ["oga", "flac"]
__COMPRESSED_MUSIC_EXTENSIONS__   = ["mp3", "ogg"]

__MUSIC_EXTENSIONS__ = __NON_COMPRESSED_MUSIC_EXTENSIONS__ + __COMPRESSED_MUSIC_EXTENSIONS__

#global variables
ogg_enc_tools = "oggenc"
ogg_enc_quality = 6


#Functions

#Les fonctions genriques
def usage() : # Cette fonction indique le mode d'emploi de ce script
	"""Print usage instruction"""
	print "usage : %s source destination" %( os.path.basename( sys.argv[0] ) )
					
	END()

# retourne l'extension du fichier
def getExtension(fileName) :
	""" Returns the file extension"""
	return fileName.split('.')[-1]

# retourne le fichier sans extension
def withoutExtension(fileName) :
	""" Returns the file path without extension"""
	return '.'.join(fileName.split('.')[0:-1])


#convertie un fichier flac vers ogg
def flac2ogg(source, destination):
	""" convert the source file from flac to ogg"""
	#print ogg_enc_quality
	print "> oggenc -q %d %s %s" % (ogg_enc_quality,ENTOURER(source), ENTOURER(destination))
	commands.getoutput("oggenc -q %d %s -o %s" % (ogg_enc_quality,ENTOURER(source), ENTOURER(destination)))

# Recopie recursivement le contenu musical du repertoire et converti		
def rec_copy_convert(src, dest):
	""" Copy recursively the multimedia contend of the directory src to dest and convert flac to ogg""" 
	INFO("Copying the directory : %s" % src )	
	for _dir in os.listdir(src) :
		_tmpSrc = src + os.sep + _dir
		_tmpDest = dest + os.sep + _dir
		#print _tmpSrc
		#print _tmpDest
		
		if os.path.isdir(_tmpSrc ) :
			MAKEDIRS(_tmpDest)
			rec_copy_convert(_tmpSrc, _tmpDest)
		
		elif os.path.isfile(_tmpSrc ) :
			
			#Is this a file to keep or to let where it is
			if ( getExtension(_tmpSrc) in __MUSIC_EXTENSIONS__) :
				if ( getExtension(_tmpSrc) in __COMPRESSED_MUSIC_EXTENSIONS__)  :
					COPY(_tmpSrc, _tmpDest)
				else :
					flac2ogg(_tmpSrc, withoutExtension(_tmpDest) + ".ogg")

def verify_folders(src, dest): # verifie la source et la destination et creer la destination si necessaire
	""" Verify if the source and destination folder exist
	    The destination folder wil be created if do not exist"""
	
	# first source
	if not ( os.path.isdir(src)) :
		ERROR("ERROR  : Cant find the directory : %s" % src)
		return False

	# destination
	if ( os.path.isdir(dest)) :
		return True
	elif ( os.path.isfile(dest)):
		ERROR("ERROR  : The  destination is a regular file : %s" % dest)
		return False
	else :
		INFO("Creation of the directory : %s" % dest)
		MAKEDIRS(dest)
		return True


#verifier la compatibilite du script
def check_compatibility():
	""" Check if your os can run this script"""
	_uname = os.uname()
	
	#OS check
	if _uname[0].lower() in ["linux", "unix"] :
		print "# Checking OS compatibility : OK"
		print "  Your OS is", _uname[0]
	else :
		print "# Checking OS compatibility : KO"
		print "  Your OS is not compatible think about a linux distribution ubuntu or debian or gentoo"
		return False

	#tools oggenc
	_status , _oggenc = commands.getstatusoutput("which oggenc")
	if _status == 0 :
		print "# Checking oggenc : OK"
		ogg_enc_tools = _oggenc
		return True
	else :
		print "# Checking oggenc : KO"
		print "  Please install oggenc tools : http://www.vorbis.com/"
		print "  For debian/Ubuntu : sudo apt-get install vorbis-tools"
		print "  For gentoo        : emerge -va media-sound/vorbis-tools"
		return False
	
#Entree principale du programme
def main() : # Cette fonction est appele lors du lancement du script
	""" Called when lunching the scrpt the main function"""	
	global ogg_enc_quality
	
	print ""
	print "flac2ogg V 0.1.0 by mzalim http://code.google.com/p/moufid"
	print ""

	#Verfier les argument de la ligne de commande
	if len(sys.argv[1:] ) != 2 :
		usage()

	_parser = OptionParser()
	_parser.add_option("-q", "--quality",
		          action="store", dest="quality", default=5,
		          help="output ogg file quality 1-10 default value is 5")
	
	(_options, _args) = _parser.parse_args()

	_source 	= os.path.abspath(_args[0])
	_destination 	= os.path.abspath(_args[1])
	ogg_enc_quality = _options.quality
	#print ogg_enc_quality
	
	if not check_compatibility() :
		ERROR("System compatibily check failed : Cant run on your system")

	#verify source and destination
	if not ( verify_folders(_source, _destination) ) :
		ERROR("ERROR : Error with source or destination directory")
	#copy now
	rec_copy_convert(_source, _destination)
	


#main entry
if __name__ == "__main__" :
	main()

